package com.zone.gateway.center.domain.manage.service;

import cn.hutool.core.collection.CollectionUtil;
import com.zone.gateway.center.application.IGatewayConfigManageService;
import com.zone.gateway.center.domain.manage.model.aggregate.ApplicationGatewayRichInfo;
import com.zone.gateway.center.domain.manage.model.entity.GatewayServerDetailEntity;
import com.zone.gateway.center.domain.manage.model.entity.GatewayServerEntity;
import com.zone.gateway.center.domain.manage.model.vo.ApplicationSystemVO;
import com.zone.gateway.center.domain.manage.model.vo.GatewayServerDetailStatus;
import com.zone.gateway.center.domain.manage.repository.IGatewayConfigManageRepository;
import com.zone.gateway.common.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/4/24
 */
@Service
public class GatewayConfigManageService implements IGatewayConfigManageService {
    @Autowired
    private IGatewayConfigManageRepository manageRepository;

    @Override
    public List<GatewayServerEntity> queryGatewayServerList() {
        return manageRepository.queryGatewayServerList();
    }

    @Override
    public void regis(GatewayServerDetailEntity gatewayServerDetail) {
        GatewayServerDetailEntity detail = manageRepository.queryGatewayServerDetail(gatewayServerDetail.getGatewayId(), gatewayServerDetail.getGatewayAddress());
        if (null == detail) {
            // 新增
            gatewayServerDetail.setStatus(GatewayServerDetailStatus.AVAILABLE.getCode());
            manageRepository.regisGatewayServerDetail(gatewayServerDetail);
        } else {
            // 更新
            manageRepository.updateGatewayServerDetailStatus(gatewayServerDetail.getGatewayId(), gatewayServerDetail.getGatewayAddress(), GatewayServerDetailStatus.AVAILABLE.getCode());
        }
    }

    @Override
    public ApplicationGatewayRichInfo queryApplicationRichInfo(String gatewayId) {
        ApplicationGatewayRichInfo applicationGatewayRichInfo = new ApplicationGatewayRichInfo();
        applicationGatewayRichInfo.setGatewayId(gatewayId);

        // 查询网关-应用映射关系
        List<String> systemIds = manageRepository.querySystemIdByGateway(gatewayId);
        List<ApplicationSystemVO> applicationSystemList = manageRepository.queryApplicaionSystemVoList(systemIds);
        applicationGatewayRichInfo.setApplicationSystemList(applicationSystemList);
        return applicationGatewayRichInfo;
    }

    @Override
    public List<String> queryGatewayIds(String systemId) {
        return manageRepository.queryGatewayIds(systemId);
    }
}
